public class change_206 {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        // 创建链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        Solution solution = new Solution();
        ListNode reversedHead = solution.reverseList(head);

        // 打印反转后的链表: 5 -> 4 -> 3 -> 2 -> 1
        printList(reversedHead);
    }

    public static void printList(ListNode node) {
        while (node != null) {
            System.out.print(node.val + " ");
            node = node.next;
        }
        System.out.println();
    }

    static class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode current = head;
            ListNode pre = null;
            ListNode temp = null;

            while (current != null) {
                temp = current.next;
                current.next = pre;
                pre = current;
                current = temp;
            }

            return pre;
        }
    }
}

